package teach.aistar.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import teach.aistar.model.entity.User;
import teach.aistar.model.vo.Result;
import teach.aistar.service.IEmailService;
import teach.aistar.service.IUserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private  IEmailService iEmailService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/logins/login")
    public String index(){
        return "login/login";
    }

    @GetMapping("/registers/register")

    public String register()
    {
        return "login/register1";
    }

    @GetMapping("/user/email")
    public String email()
    {
        return "login/email";
    }

    @RequestMapping("/send")
    @ResponseBody
    public Result emailsend(HttpServletRequest request, HttpSession session)
    {

        String email = request.getParameter("email");

        System.out.println("您传的邮箱为："+ email);

        iEmailService.send(email);


        session.setAttribute("email",email);

//        ValueOperations vop = redisTemplate.opsForValue();
//        String code = (String) vop.get("user_code");

//        request.setAttribute("code",code);





            return new Result("200", "发送成功", null);




    }

    @RequestMapping("/code")
    @ResponseBody
    public Result emailYZ(HttpServletRequest request,HttpSession session)
    {

        String code = request.getParameter("code");

        String email = (String) session.getAttribute("email");


        ValueOperations vop = redisTemplate.opsForValue();
        String coder = (String) vop.get("code_"+email);





        if(code.equals(coder))
        {

            User user = new User();
            user.setUname(email);
            user.setPower(1);
            session.setAttribute("uname",email);
            session.setAttribute("User",user);
            iUserService.add(user);

            return new Result("200", "邮箱验证码正确", null);

        }




        if(coder==null)

            return new Result("400","邮箱验证码已失效，请重新发送",null);

        else
            return new Result("401","邮箱验证码错误",null);
    }

}
